<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>文件分片上传/下载测试</title>
  <script src="./js/jquery.min.js"></script>
  <script src="./js/spark-md5.min.js"></script>
  <style>
    html,
    body {
      width: 100%;
      height: 100vh;
      margin: 0;
    }

    header {
      height: 30px;
      display: flex;
      align-items: center;
      margin: 0;
      padding: 10px;
      background-color: #333;
      color: white;
    }

    header>h1 {
      font-size: 18px;
    }

    main {
      height: calc(100% - 100px);
    }

    .uploadBox {
      height: 100%;
      display: flex;
      padding: 10px;
      font-size: 14px;
    }
  </style>
</head>

<body>
  <header>
    <h1>文件分片上传测试页面</h1>
  </header>
  <main>
    <div class="uploadBox" id="upload-box">
      <div class="chooseFile">
        <label for="file">选择文件：</label>
        <button id="selectFile">选择文件</button>
        <div class="fileInfo">
          <p id="fileName">文件名称：</p>
          <p id="fileSize">文件大小：</p>
          <label for="chunkSize">分片大小：</label><input value="1024" id="chunkSize" type="number" placeholder="分片大小"><span>
            kb</span>
        </div>
        <input hidden type="file" id="file">
        <button style="width: 100%; margin-top:10px;">开始上传</button>
        <p id="uploadInfo"></p>
      </div>
    </div>
  </main>
  <script>
    $(document).ready(function () {
      $('#selectFile').click(() => {
        $('#file').click();
      });
      $('#file').change(async (e) => {
        var chunkSize = $('#chunkSize').val() * 1024;
        if (chunkSize == 0) {
          alert('分片大小不可以为0')
          return;
        }
        var file = e.target.files[0]
        $('#fileSize').append(Math.ceil(file.size / 1024) + ' kb')
        $('#fileName').append(file.name)
        //进行文件分割并上传
        sliceFileAndUpload(e.target.files, chunkSize)
      })
    });

    function sliceFileAndUpload(files, chunkSize) {
      var filePartList = [];
      var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        file = files[0],
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();
      fileReader.onload = e => {
        spark.append(e.target.result);
        currentChunk++;
        if (currentChunk < chunks) {
          loadNext();
        } else {
          var uid = spark.end();
          filePartList.forEach(item => {
            let formData = new FormData();
            formData.append('file', item.filePart);
            formData.append('uid', uid);
            formData.append('currentIndex', item.currentIndex);
            formData.append('fileName', file.name);
            formData.append('totalSize', file.size);
            $.ajax({
              url: '/file/uploadBySlice',
              method: 'POST',
              data: formData,
              processData: false,
              contentType: false,
              success: function (e) {
                console.log(e)
                $('#uploadInfo').append(e + "<br/>")
              }
            })
          })
          alert('上传完成，请到测试文件夹验证文件是否正确')
        }
      }
      fileReader.onerror = () => {
        console.log('文件读取处理发生错误')
      }
      function loadNext() {
        var temp = {}
        var start = currentChunk * chunkSize,
          end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        let filePart = blobSlice.call(file, start, end);
        temp.currentIndex = start;
        temp.filePart = filePart;
        filePartList.push(temp);
        fileReader.readAsArrayBuffer(filePart);
      }
      loadNext();
    }
  </script>
</body>

</html>